﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Office = Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using r2mp.Classes;

// TODO:  Follow these steps to enable the Ribbon (XML) item:

// 1: Copy the following code block into the ThisAddin, ThisWorkbook, or ThisDocument class.

//  protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
//  {
//      return new r2mpRibbonsTab();
//  }

// 2. Create callback methods in the "Ribbon Callbacks" region of this class to handle user
//    actions, such as clicking a button. Note: if you have exported this Ribbon from the Ribbon designer,
//    move your code from the event handlers to the callback methods and modify the code to work with the
//    Ribbon extensibility (RibbonX) programming model.

// 3. Assign attributes to the control tags in the Ribbon XML file to identify the appropriate callback methods in your code.  

// For more information, see the Ribbon XML documentation in the Visual Studio Tools for Office Help.


namespace r2mp_Excel
{
    [ComVisible(true)]
    public class r2mpRibbonsTab : Office.IRibbonExtensibility
    {
        private Office.IRibbonUI ribbon;
        private Excel.Application app;
        private Excel.Worksheet active;
        private Dialog dialog = new Dialog();
        private int period = 0;
        private Task start = new Task();

        public r2mpRibbonsTab()
        {

        }

        public void CreateMTA(Office.IRibbonControl control)
        {
            app = Globals.ThisAddIn.Application;
            active = ((Excel.Worksheet)app.ActiveSheet);
            int rows = CountRows();
            if (rows == 0)
            {
                MessageBox.Show("Arbeitsblatt besitzt kein gültiges Format");
            }
            else
            {
                try
                {
                    MTA milestones = new MTA();
                    for (int i = 0; i < rows; i++)
                    {
                        milestones.Milestones.Add(CreateMilestone(i));
                    }
                }
                catch (FormatException e)
                {
                    MessageBox.Show("Das Blatt enthält ungültige Daten");
                }
            }
        }

        private Milestone CreateMilestone(int i)
        {
            List<DateTime> dates = new List<DateTime>();
            // +1 wegen 0; +1 wegen Titel
            i = i + 2;
            int offset = 0;
            char inital = 'B';

            Milestone re = new Milestone();
            DateTime second = DateTime.Now;
            if (offset == 0)
            {
                re.Name = active.get_Range(inital + "" + i).Value2 + "";
                offset++;
                inital = (char)((int)'B' + offset);
            }
            while (!(active.get_Range(inital + "" + i).Value2 + "").Equals(""))
            {
                try
                {
                    if (!(active.get_Range(inital + "" + i).Value + "").Equals("NV"))
                    {
                        second = DateTime.Parse(active.get_Range(inital + "" + i).Value + "");
                        if (re.Timeshifts.Count == 0)
                        {
                            re.PlannedCompletionDate = DateTime.Parse(active.get_Range(inital + "" + i).Value + "");
                            dates.Add(DateTime.Parse(active.get_Range(inital + "" + i).Value + ""));
                            re.Timeshifts.Add(0);

                        }
                        else
                        {
                            if (dates[dates.Count - 1] != second)
                            {
                                re.Timeshifts.Add(GetOffset(dates[dates.Count - 1], second));
                            }
                            else
                            {
                                re.Timeshifts.Add(0);
                            }
                            dates.Add(second);
                        }
                    }
                        offset++;
                        inital = (char)((int)'B' + offset);
                }
                catch (FormatException e)
                {
                    throw e;
                }
            }
            return re;
        }

        private int GetOffset(DateTime from, DateTime to)
        {
            int re = 0;
            if (from < to)
            {
                while (from < to)
                {
                    if (period == 0)
                    {
                        from = from.AddMonths(1);
                    }
                    else
                    {
                        from = from.AddDays(7);
                    }
                    re++;
                }
            }
            else
            {
                while (from > to)
                {
                    if (period == 0)
                    {
                        to = to.AddMonths(1);
                    }
                    else
                    {
                        to = to.AddDays(7);
                    }
                    re--;
                }
            }
            //MessageBox.Show(re + "");
            return re;
        }

        public void CreatePSP(Office.IRibbonControl control)
        {
            app = Globals.ThisAddIn.Application;
            active = ((Excel.Worksheet)app.ActiveSheet);
            Task temp;
            int rows = CountRows();
            try
            {
                for (int i = 0; i < rows; i++)
                {
                    temp = CreateTask(i);
                    AddTask(start, temp);
                }
            }
            catch (FormatException e)
            {
                MessageBox.Show("Falsches Format der Daten");
            }
        }

        private void AddTask(Task start, Task temp)
        {
            String[] parts = temp.Nr.Split('.');
            Task temptemp = start;
            for (int i = 0; i < parts.Length - 1; i++)
            {
                temptemp = temptemp.Tasks[Int32.Parse(parts[i]) - 1];
            }
            temptemp.Tasks.Add(temp);
        }

        private Task CreateTask(int i)
        {
            try
            {
                i += 2;
                Task now = new Task();
                now.Nr = active.get_Range("A" + i).Value + "";
                now.Name = active.get_Range("B" + i).Value + "";
                //MessageBox.Show(active.get_Range("C" + i).Value + "");
                now.Status = GetStatus(Double.Parse((active.get_Range("C" + i).Value + "")));
                CreateReassource(now, (active.get_Range("D" + i).Value + ""));
                return now;
            }
            catch (FormatException e)
            {
                throw e;
            }
        }

        private void CreateReassource(Task now, dynamic dynamic)
        {
            String res = dynamic + "";
            String[] temp = res.Split(';');
            now.Ressources = new List<string>();
            for (int i = 0; i < temp.Length; i++)
            {
                now.Ressources.Add(temp[i]);
            }
        }

        private int GetStatus(double p)
        {
            if (p == 0)
            {
                return Task.Pending;
            }
            else if (p == 1)
            {
                return Task.Finished;
            }
            else
            {
                return Task.Started;
            }
        }

        private int CountRows()
        {
            int re = 1;
            int temp;
            bool end = false;
            if (active != null)
            {
                while (!end)
                {
                    temp = re + 1;
                    if (!(active.get_Range("A" + temp).Value + "").Equals(""))
                    {
                        re++;
                    }
                    else
                    {
                        end = true;
                    }
                }
            }
            else
            {
                MessageBox.Show("Bitte Artbeitsmappe öffnen, bevor sie PMP starten");
            }
            return re - 1;
        }

        #region IRibbonExtensibility Members

        public string GetCustomUI(string ribbonID)
        {
            return GetResourceText("r2mp_Excel.r2mpRibbonsTab.xml");
        }

        #endregion

        #region Ribbon Callbacks
        //Create callback methods here. For more information about adding callback methods, select the Ribbon XML item in Solution Explorer and then press F1

        public void Ribbon_Load(Office.IRibbonUI ribbonUI)
        {
            this.ribbon = ribbonUI;
        }

        #endregion

        #region Helpers

        private static string GetResourceText(string resourceName)
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            string[] resourceNames = asm.GetManifestResourceNames();
            for (int i = 0; i < resourceNames.Length; ++i)
            {
                if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
                {
                    using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
                    {
                        if (resourceReader != null)
                        {
                            return resourceReader.ReadToEnd();
                        }
                    }
                }
            }
            return null;
        }

        #endregion
    }
}
